package com.example.md5.demo;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;

import android.app.Activity;
import android.os.Bundle;

/**
 * Good
 * 
 * @author Le Xuan Vu
 * 
 */

public class MainActivity extends Activity {

	String sTest = "lexuanvu";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		System.out.println(md5(sTest));
	}

	public String md5(String string) {
		if (string == null || string.trim().length() < 1) {
			return null;
		}
		try {
			return getMD5(string.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	private String getMD5(byte[] source) {
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			StringBuffer result = new StringBuffer();
			// lay tung 4 bit nhi phan sau do cong voi 1111 roi chuyen sang hexa
			for (byte b : md5.digest(source)) {			
				result.append(Integer.toHexString((b & 0xf0) >>> 4)); // lay 4 bit dau chuyen sang he hex				
				result.append(Integer.toHexString(b & 0x0f));// lay 4 bit sau chuyen sang he hex				
			}
			return result.toString();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}
}
